package com.servlet;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import com.easywan.exception.FileExtErrorExcetion;
import com.easywan.exception.RuleErrorException;
import com.easywan.utils.Config;

public class DefaultUploadServlet extends AbsBaseUploadServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	public Long getFileSizeMax() {
		return 1024 * 1024 * 50L;
	}

	@Override
	public String getSavePath() {
		return Config.get("fileSavePath");
	}

	@Override
	public String getDestPath() {
		if(isDest()){
			return Config.get("fileDestSavePath");
		}
		return null;
	}

	@Override
	public String getTmpPath() {
		return Config.get("fileTmpSavePath");
	}

	@Override
	public boolean isExt(String string) {
		return true;
	}
	@Override
	/*
	 * (non-Javadoc)
	 * @see com.servlet.AbsBaseUploadServlet#isDest()
	 */
	public boolean isDest() {
		return false;
	}
	public void saveFile(FileItem file, String fileNameAttr) throws IOException {
		 InputStream is = file.getInputStream();
		 String fileAttr = getFileName(fileNameAttr);
         FileOutputStream out = new FileOutputStream(getSavePath()+"/"+fileAttr);
         System.out.println("保存源文件，文件所在路径:" + getSavePath()+"/"+fileAttr);
         //创建一个缓冲区
         byte buffer[] = new byte[1024];
         //判断输入流中的数据是否已经读完的标致
         int len = 0;
         while((len = is.read(buffer)) > 0){
             out.write(buffer, 0, len);
         }
       
         //关闭输出流
         out.close();
         //关闭输入流
         is.close();
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
		try {
				@SuppressWarnings("unchecked")
				Map<String,Object> params = (Map<String, Object>) req.getAttribute("params");
				for(String key : params.keySet()){
					Object value = params.get(key);
					if(value instanceof FileItem){
						FileItem file = (FileItem) value;
						String fileName = file.getName();
						  String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						 if(this.isExt(fileExt)){
							 saveFile(file,fileName);
						 }else{
							throw new FileExtErrorExcetion();
						 }
					}
				}
			}catch(FileNotFoundException e) {
				e.printStackTrace();
			}catch(IOException e){
				e.printStackTrace();
			}catch (FileExtErrorExcetion e) {
				e.printStackTrace();
			}
		
	}
}
